var threshold = 9.6556;
var index = -1;
var array = [7, 8, 12, 14];
var visited = [false, false, false, false];
var advice = '1.检查物料C进料阀门是否漏液；<br />2.加大物料C进料泵功率<br />,1.检查/调整物料A进料阀门开启情况；<br />2.检查/调整惰性气体B进料速度；<br />3.检查/调整物料C进料阀门开启情况<br />,' +
    '检查/降低冷凝器冷却水预设温度<br />,检查/调整反应器冷却水阀门开启情况';
var str = "物料C压力头损失,物料A，B，C的组成发生变化,冷凝器冷却水入口温度发生变化,反应器冷却水阀门";
var info = str.split(",");
var padvice = advice.split(",");

var inter1 = 0;
var inter2 = 0;
var interval = 0;
var intervalArray = [];
var bgm = "../static/audio/alter.mp3";
bgm = new Audio(bgm);
var chartDom = document.getElementById('cha');
var myChart = echarts.init(chartDom);
var option = {
    tooltip: {
        trigger: 'none',
        axisPointer: {
            type: 'cross'
        }
    },
    xAxis: {
        type: 'category',
        data: [],
        axisLine: {
            onZero: false,
            lineStyle: {
                color: '#5470C6'
            }
        },
    },
    yAxis: {
        type: 'value',
        axisLine: {
            onZero: false,
            lineStyle: {
                color: '#5470C6'
            }
        },
    },
    visualMap: {
        show: false,
        pieces: [
            {
                gt: 0,
                lte: threshold, //这儿设置基线上下颜色区分 基线下面为绿色
                color: '#03d6d6'
            },
            {
                gt: threshold, //这儿设置基线上下颜色区分 基线上面为红色
                color: '#e91642'
            }
        ]
    },
    series: [
        {
            data: [],
            type: 'line',
            smooth: true,
            symbol: 'none',
            markLine: {
                silent: true,
                lineStyle: {
                    normal: {
                        color: '#01fef9' // 这儿设置安全基线颜色
                    }
                },
                data: [
                    {
                        yAxis: threshold
                    }
                ],
                label: {
                    normal: {
                        formatter: '安全\n基线' // 这儿设置安全基线
                    },
                    padding: {
                        padding: 0
                    }
                }
            }
        }
    ]
};
//初次加载时提示等待
commonUtil.message("监测系统初始化中……", "info", 3000)
option && myChart.setOption(option);
index = getRandomType(true);

visited[index] = true;
updateData(array[index], "True");

function initAll() {
    // clearAll();
    bgm.pause();
    for (var j = 0; j < array.length; j++) {
        var change = document.getElementById(array[j] + "");
        change.style = "height: 25px;width:25px;background-color: green;border:none;margin-right:20px;border-radius:50%;";
    }
    document.getElementById("advice-right").innerHTML = "";
    document.getElementById("work1").innerHTML = "工作状态:正常";
    document.getElementById("work1").style = "font:bold 25px Arial, Helvetica, sans-serif;color:#fff ;"
    document.getElementById("work4").innerHTML = "故障种类：--";
    option.series[0].data = [];
    option.xAxis.data = [];
    option && myChart.setOption(option);
}

function updateData(i, cache) {

    initAll()
    $('#bounce').attr('disabled', 'disabled');
    $('#bounce').css('background-color', '#cccccc');

    $('#formid').attr('disabled', 'disabled');
    $('#formid').css('background-color', '#cccccc');

    $('#message').attr('disabled', 'disabled');
    $('#message').css('background-color', '#cccccc');
    $.ajax({
        type: "POST",
        url: "/detect",
        dataType: 'json',
        data: {"kinds": i, "cache": cache},
        error: function () {
            console.log("error")
        },
        success: function (res) {
            var bgmOpen = false;
            originData = res["detect_data"].reverse();
            for (var j = 0; j < originData.length; j++) {
                if (originData[j] >= 2 * threshold) {
                    originData[j] = 2 * threshold;
                }
            }
            var X = Array(originData.length);
            for (j = 0; j < originData.length; j++) {
                X[j] = j + 1;
            }
            X.reverse();
            countError = 0;
            interval = setInterval(function () {
                if (originData.length) {
                    if (countError === 3) {
                        if (!bgmOpen) {
                            bgmOpen = !bgmOpen;
                            bgm.play(); //播放 mp3这个音频对象
                            $(bgm).bind("ended", function () {
                                bgm.play();
                            });
                            flashText();
                            errorMessage.message("系统检测到故障！分类中……", "danger")
                            sleep(cache === "True" ? 3000 : 0).then(() => {
                                classify(i, cache)
                            })
                        }
                    }
                    if (originData[originData.length - 1] > threshold) {
                        countError++;
                    }
                    option.series[0].data.push(originData.pop());
                    option.xAxis.data.push(X.pop());
                    myChart.setOption(option);
                } else {
                    clearInterval(interval)
                    console.log(res["detect_rate"])
                }
            }, 50)
            intervalArray.push(interval)

        }
    })
}


$("#bounce").click(function () {
    initAll();
    commonUtil.message("系统状态已恢复，即将开始监测……");
    index = getRandomType(false);
    updateData(array[index], "False");
});
$("#message").click(function () {
        commonUtil.message("邮件正在发送中……", "info")
        $.ajax({
            type: "POST",
            url: "/sendEmail",
            dataType: 'json',
            data: {
                'kind': array[index]
            },
            success: function () {
                commonUtil.message("已通知管理员和维修人员！")
            }
        })
    }
);

function getRandomType(cache) {
    var last = -1
    $.ajax({
        type: "POST",
        url: "/lastFault",
        dataType:"json",
        async:false,
        success: function (data) {
            if (data['lastFault'] !== "None")
                last = eval(data["lastFault"])
        },
    })
    if (!cache || last === -1) {
        for (var i = 0; i < array.length; i++) {
            if (!visited[i])
                break;
        }
        if (i === array.length) {
            for (i = 0; i < array.length; i++)
                visited[i] = false;
        }
        while (true) {
            var res = Math.round(Math.random() * array.length) % array.length;
            if (!visited[res])
                return res;
        }
    } else {
        for (let i = 0; i < array.length; i++) {
            if (array[i] === last)
                return i;
        }
    }
}

function flashText() {
    //闪字
    document.getElementById("work1").innerHTML = "工作状态:故障";
    document.getElementById("work1").style = "font:bold 25px Arial, Helvetica, sans-serif;color:#ac2925 ;"
    inter1 = setInterval(litSlash, 500);
    intervalArray.push(inter1)

    function litSlash() {
        document.getElementById("work1").animate({opacity: "0"}, 250);
        document.getElementById("work1").animate({opacity: "1"}, 499);
    }

}

function flashLight() {
    //闪灯
    var change = document.getElementById(array[index] + "");
    change.style = "height: 25px;width:25px;background-color: red;border:none;margin-right:20px;border-radius:50%";

    function litSlash() {
        change.animate({opacity: "0"}, 250);
        change.animate({opacity: "1"}, 499);
    }

    inter2 = setInterval(litSlash, 500);
    intervalArray.push(inter2)
}

function clearAll() {
    for (var i = intervalArray.length - 1; i >= 0; i--) {
        if (intervalArray[i]) {
            clearInterval(intervalArray[i])
            intervalArray.pop()
        }
    }
}

function add_info() {
    $.ajax({
        //几个参数需要注意一下
        type: "POST",//方法类型
        dataType: "json",//预期服务器返回的数据类型
        url: "/formProcess",//url
        data: $("#form_data").serialize(),
        success: function () {
            alert("记录已提交！")
        },
    });
}

function classify(i, cache) {
    $.ajax({
        type: "POST",
        url: "/calcRate",
        dataType: "json",
        data: {
            "kinds": i,
            "cache": cache
        },
        error: function () {
            console.log("ajax error")
        },
        success: function (res) {
            console.log(res["classification_rate"])
            //恢复按钮使用
            $('#bounce').removeAttr('disabled');
            $('#bounce').css('background-color', '#337ab7');

            $('#formid').removeAttr('disabled');
            $('#formid').css('background-color', '#337ab7');

            $('#message').removeAttr('disabled');
            $('#message').css('background-color', '#337ab7');

            flashLight();
            document.getElementById("work4").innerHTML = "故障种类：" + array[index] + "—" + info[(index + 1) % info.length];
            errorMessage.message("分类结束!故障种类为:" + array[index] + ",左侧红灯表示故障发生位置", "danger")
            document.getElementById("advice-right").innerHTML += "维修建议:<br />" + padvice[index];
        }
    })
}

function sleep(time) {
    return new Promise((resolve) => setTimeout(resolve, time));
}